﻿using AutoMapper;
using B.S.Database.Domain.Entity;
using B.S.Database.ErrorCode;
using B.S.Database.Interface.Interface;
using B.S.Database.Write.Api.Application.Commands.Traceability;
using MediatR;
using System;
using System.IO;

namespace B.S.Database.Write.Api.Application.CommandHandler.Traceability
{
    public class TraceabilityCreateCommandHandler : IRequestHandler<TraceabilityCreateCommands, Apiresult<object>>
    {
        private readonly IBaseResotity<Basic_Traceability> traceabilityReposity;
        private readonly IMapper mapper;

        public TraceabilityCreateCommandHandler(IBaseResotity<Basic_Traceability> TraceabilityReposity,IMapper mapper)
        {
            traceabilityReposity = TraceabilityReposity;
            this.mapper = mapper;
        }

        public  Task<Apiresult<object>> Handle(TraceabilityCreateCommands request, CancellationToken cancellationToken)
        {
            Apiresult<object> res = new Apiresult<object>();
            using (var tran = traceabilityReposity.Db.Database.BeginTransaction())
            {
                try
                {
                    var entity = mapper.Map<Basic_Traceability>(request);
                    entity.CreateName = request.CreateName;
                    entity.CreateTime = DateTime.Now;
                    traceabilityReposity.Add(entity);
                    res.Code = ApiEnums.成功;
                    res.Message = ApiEnums.成功.ToString();
                    res.Data = entity.TraceabilityId; // 返回主键或其它信息
                    tran.Commit();
                }
                catch (Exception ex)
                {
                    res.Code = ApiEnums.错误;
                    res.Message = ApiEnums.错误.ToString();
                    res.Message = ex.Message;
                    tran.Rollback();
                }
            }
            return Task.FromResult(res);
        }
    }
}
